package davel

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"math/rand"
	"net/url"
	"os"
	"os/exec"
	"regexp"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"time"
)

func RunCmd(cmd string) ([]byte, error) {
	if runtime.GOOS == "windows" {
		return exec.Command("cmd", "/c",cmd).Output()
	} else {
		return exec.Command("/bin/sh", "-c",cmd).Output()
	}
}

func GetPwd() string {
	dir, _ := os.Getwd()
	return FileRealPath(dir)
}

func Md5(str string) string  {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

func Preg_match(pattern string, str string) ([]string, error) {
	digitsRegexp := regexp.MustCompile(pattern)
	preg_matches := digitsRegexp.FindStringSubmatch(str)
	if len(preg_matches)<=0 {
		return nil, errors.New("none")
	}
	return preg_matches[1:],nil
}

func StrToInt(str string) int  {
	r,err := strconv.Atoi(str)
	if err!=nil {
		return 0
	}
	return r
}

func StrToInt64(str string) int64  {
	r, err := strconv.ParseInt(str, 10, 64)
	if err!=nil {
		return 0
	}
	return r
}

func IntToStr(num int) string {
	return strconv.Itoa(num)
}

func Int64ToStr(num int64) string  {
	return strconv.FormatInt(num,10)
}


func ArrayUnshift(key interface{},args ...interface{}) []interface{} {
	parmas := make([]interface{}, 0)
	parmas = append(parmas, key)
	if len(args) > 0 {
		for _, v := range args {
			parmas = append(parmas, v)
		}
	}
	return parmas
}

//获取当前毫秒
func GetMillisecond() int64 {
	return time.Now().UnixNano() / int64(time.Millisecond)
}

//签名
func GenerateSign(appkey string,params map[string]string) string  {
	var sslice []string
	for key, _ := range params {
		sslice = append(sslice, key)
	}
	// 1. 字典升序排序
	sort.Strings(sslice)

	// 2. 拼按URL键值对
	str := ""
	for _, v := range sslice {
		if len(params[v])>0 {
			str += v+"="+ url.QueryEscape(params[v]) +"&"
		}
	}
	// 3. 拼接app_key
	str += "app_key=" + appkey
	// 4. MD5运算+转换大写，得到请求签名
	sign := Md5(str)
	return strings.ToUpper(sign)
}

//签名
func MapToSting(params map[string]string) string  {
	str := ""
	for k, v := range params {
		str += k +"="+ v +"&"
	}
	return str[:len(str)-1]
}

//读取图片为base64
func ImgBase64(filename string) (string,error) {
	bytes,err := File2Bytes(filename)
	if err!=nil {
		return "",errors.New("none")
	}
	return base64.StdEncoding.EncodeToString(bytes),nil
}

/**
随机整数
unsigned true正整数  false可为负数
*/
func randInt(num int,unsigned bool) int  {
	number := rand.Intn(num)
	if !unsigned {
		n := rand.Intn(2)
		if n==1 {
			number *= -1
		}
	}
	return  number
}

func StringsContains(array []string, val string) (index int) {
	for index,value := range array{
		if val==value {
			return  index
		}
	}
	return -1
}